package com.example.iotmanagerment26.service.impl;

import com.example.iotmanagerment26.domain.Device;
import com.example.iotmanagerment26.domain.DeviceHold;
import com.example.iotmanagerment26.domain.vo.DeviceHoldVO;
import com.example.iotmanagerment26.mapper.DeviceHoldMapper;
import com.example.iotmanagerment26.mapper.DeviceMapper;
import com.example.iotmanagerment26.service.DeviceHoldService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeviceHoldServiceImpl implements DeviceHoldService {

    @Resource
    DeviceHoldMapper deviceHoldMapper;
    @Resource
    Device device;
    @Resource
    DeviceMapper deviceMapper;

    @Override
    public int userBindDevice(DeviceHold dh) {
        //1.检查devicehold2表中是否有记录
        //2.如果有，修改devicehold2的holded字段
        //3.如果没有，在devicehold2表中插入一条记录
        //4.修改device表中的usercount字段

        DeviceHold dhresult = deviceHoldMapper.selectHoldByUserAndDevice(dh);
        //假如devichold表中已经有记录
        if (dhresult != null) {
            //看holded字段的值
            if (dhresult.getHolded() == 0) {
                dhresult.setHolded(1);
                int j = deviceHoldMapper.updateDeviceHold(dhresult);
                if (j >= 1) {

                    device.setName(dh.getDevName());
                    return deviceMapper.updateDevice(device);
                } else {
                    return 0;
                }
            }else{
                return 0;
            }
        }
        //devicehold表中没有记录
        else {
            int i = deviceHoldMapper.insertDeviceHold(dh);
            if (i >= 1) {
                device.setName(dh.getDevName());
                return deviceMapper.updateDevice(device);
            } else {
                return 0;
            }
        }
    }

    @Override
    public List<Device> selectUnbindDeviceByUser(String username) {
        return deviceHoldMapper.selectUnbindDeviceByUser(username);
    }

    @Override
    public List<DeviceHoldVO> selectAllDeviceHoldList() {
        return deviceHoldMapper.selectAllDeviceHoldList();
    }

    @Override
    public int unBind(DeviceHold devicehold) {
        DeviceHold dhresult = deviceHoldMapper.selectHoldByUserAndDevice(devicehold);
        if(dhresult!=null ){
            if(dhresult.getHolded()==1){
                int i=deviceHoldMapper.updateDeviceHold(devicehold);
                if(i>=1){
                    //解绑成功
                    return deviceMapper.reduceUserCount(devicehold.getDevName());
                }else{
                    //解绑失败
                    return 0;
                }

            }else{
                //holded==0不处于绑定状态
                return 0;
            }

        }else{
            //没有这条记录
            return 0;
        }
    }

    @Override
    public List<Device> selectbindDeviceByUser(String username) {
        return deviceHoldMapper.selectbindDeviceByUser(username);
    }
}
